package com.slaoren.mvvmexamp.ui

import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import com.slaoren.mvvmexamp.R
import com.slaoren.mvvmexamp.databinding.ActivityMvvmDemoBinding
import com.slaoren.mvvmexamp.vm.DemoViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope

/**
 * 横竖屏切换实现示例之一：
 * Activity和Fragment保持原有横竖屏切换逻辑，每次横竖屏切换都重建Fragment，通过mvvm实现Fragment横竖屏数据共享。
 * 如果切换横竖屏已有的Fragment未重建可先从fragmentManager.beginTransaction().remove()清除掉Fragment对象。
 */
class MvvmDemo1Activity: BaseActivity<ActivityMvvmDemoBinding, DemoViewModel>(),View.OnClickListener, CoroutineScope by MainScope() {

    var currentFragmentTag = "fragment"
    override fun getLayoutId(): Int {
        return R.layout.activity_mvvm_demo
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }
    override fun initView() {
        mBinding.vm = mViewModel
        changeFragment(currentFragmentTag)
    }
    override fun setObserve() {
    }
    override fun loadData() {
    }

    private fun changeFragment(tag: String) {
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()
        for (fragmentManagerFragment in fragmentManager.fragments) {
            fragmentTransaction.hide(fragmentManagerFragment)
        }
        var fragment = fragmentManager.findFragmentByTag(tag)
        if (fragment != null) {
            fragmentTransaction.show(fragment)
        } else {
            fragment = when(tag){
                "fragment"->MvvmDemoFragment()
//                "xx"->xxFragment()
//                "oo"->ooFragment()
                else -> null
            }

            if (fragment != null) {
                fragmentTransaction.add(R.id.frameLayout, fragment, tag)
            }
        }
        fragmentTransaction.commitNow()
    }

    override fun onClick(p0: View?) {
        //控件点击事件切换fragment
//        when(p0){
//            xx->currentFragmentTag = "xx"
//            oo->currentFragmentTag = "oo"
//            fragment->currentFragmentTag = "fragment"
//        }
//        changeFragment(currentFragmentTag)
    }
}